<?php 
namespace App\Http\Controllers\Device;

use App\Http\Controllers\Controller;
use App\Utils\MultipleAccounts;
use App\Utils\UploadToQiniu;
use Illuminate\Http\Request;

use Qiniu\Auth;
use Qiniu\Processing\PersistentFop;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

set_time_limit(800);
class RecorderController extends Controller {


    /*
     * 将第三方链接视频上传到七牛
     */
	protected function uploadtoqiniu($tmp_path, $type = 1){


		$qiniu_token = qiniu_token('reportsource');

		$path = explode('/', $tmp_path);

		if ($qiniu_token['status_code'] == 200) {
			
			// $token = $qiniu_token['data']['token'];

			if ($type == 2){

			    // 去掉url中get后缀
                $remove_houzhui = explode('?', $tmp_path);
                $path_2 = explode('/', $remove_houzhui[0]);
                $file_name = $qiniu_token['data']['key'] . $path_2[count($path_2) - 1];
            }else{
                $file_name = $qiniu_token['data']['key'] . $path[count($path) - 1];
            }

			//---
			$auth = new Auth(config('upload.accessKey'),config('upload.secretKey'));
			//拼接字符串
			$fetch = \Qiniu\base64_urlSafeEncode($tmp_path);
			$to = \Qiniu\base64_urlSafeEncode(config('upload.bucket_report') . ':' . $file_name);

			$host = 'http://iovip.qbox.me';

			$url = '/fetch/' . $fetch . '/to/' . $to;
			//签名
			$sign = $auth->sign($url . "\n");
			//print_r(parse_url($url));exit;
			$res = curlinfo_header('POST', $host . $url, ['Content-Type: application/json', 'Authorization: QBox ' . $sign], []);

			if (is_array(json_decode($res, true))) {
				
				$res_arr = json_decode($res, true);
				// print_r($qiniu_token);
				// print_r($res_arr);exit;

				return isset($res_arr['key']) ? ['url' => config('upload.bucket_report_domain') . $res_arr['key'], 'type' => $res_arr['mimeType']] : false;
			}else{

				return false;
			}

		}else{

			return false;
		}

	}


    /**
     * 记录仪一键举报(盯盯拍)
     * @param  Request $request [description]
     * @return \Symfony\Component\HttpFoundation\Response [type]           [description]
     */
	public function device_report(Request $request){
        
        $mobile = $request->input('phone', '');
        $device_id = $request->input('device_id', '');
        $report_time = $request->input('report_time', '');
        $locale = $request->input('locale', '');
        $report_GPS = $request->input('report_GPS', '');
        $device_file = $request->input('device_file', '');
        
        $api_url = 'https://api.jtpk668.com/web/';
        
        if (!$device_id || !$report_time || !$locale || !$report_GPS || !$device_file || !$mobile) {
            
            return response()->json(['status_code' => 400, 'msg' => '参数不足']);
            
        } else {
    
            // 写入举报的设备 id 和手机号
            @file_put_contents('ddp', 'device_id:' . $device_id . 'mobile:' . $mobile . "\r\n");
            
            // 盯盯拍地址不进行转换
            //$locale = $this->getLocate($locale, $report_GPS);
            
            //2.获取上传文件路径，上传到七牛
            // 使用新版上传
            $qiniu_config = array(
                'accessKey' => config('upload.accessKey'),
                'secretKey' => config('upload.secretKey'),
                'bucket'    => config('upload.bucket_report'),
                'domain'    => config('upload.bucket_report_domain'),
            );
            $upload_to_qiniu = new UploadToQiniu($qiniu_config);
            $upload_result = $upload_to_qiniu->fetch($device_file);
            
            if ($upload_result['status']){
                
                $result = json_decode(curlinfo_header('POST', $api_url . 'recorder_ddp_report', [], [
                    'mobile' => $mobile,
                    'device_id' => $device_id,
                    'report_time' => $report_time,
                    'locale' => $locale,
                    'report_GPS' => $report_GPS,
                    'file_key' => $upload_result['key']
                ], true), true);
                
                if ($result['status_code'] == 200) {
                    // 举报成功
                    return response()->json(['status_code' => 200, 'data' => ['create_time' => date('Y-m-d H:i:s', time())]]);
                }else {
                    
                    return response()->json(['status_code' => $result['status_code'], 'msg' => $result['msg']]);
                }
            }
            
        }
	}


    /**
     * 海康一键举报
     * @param  Request $request [description]
     * @return \Symfony\Component\HttpFoundation\Response [type]           [description]
     */
	public function device_report_hk(Request $request){
		
		$device_id = $request->input('device_id', '');
		$report_time = $request->input('report_time', '');
		// $locale = $request->input('locale', '');
		$start_GPS = $request->input('start_GPS', null);
		$end_GPS = $request->input('end_GPS', null);
		$type = 'haikang';
		$api_url = 'https://api.jtpk668.com/web/';
		//默认uid
		$uid = 'M0000000716637';
		
		if (!$device_id || !$report_time || !$start_GPS || !$end_GPS) {
			
			return response()->json(['status_code' => 400, 'msg' => 'request error']);

		}
		// 没有收到上传文件
		if (!$request->hasFile('device_file') || !$request->file('device_file')->isValid()) {

		    return response()->json(['status_code' => 400, 'msg' => 'params error']);
		}

		//根据设备码获取uid
		$userbydevice = json_decode(curlinfo_header('GET', $api_url . 'user/getUserByDevice?device_id=' . $device_id . '&type=' . $type, [], []), true);

		if ($userbydevice['status_code'] == 200 && isset($userbydevice['data']['uid'])) {

			$uid = $userbydevice['data']['uid'];
		}

		if ($uid != 'M0000000716637') {
			//  添加或更新机器码
			curlinfo_header('POST', $api_url . '/user/setDeviceByUser', [], ['uid' => $uid, 'device_id' => $device_id, 'type' => $type]);
		}
		// 获取用户信息
		$userinfo = self::$db->table('app_userinfo')
				->select('USERID','MOBILE')
				->where('USERID', '=', $uid)
				->first();

		// 上传文件到七牛并转码成mp4
		$files = $request->file('device_file');

        $auth = new Auth(config('upload.accessKey'),config('upload.secretKey'));
        $bucket = config('upload.bucket_report');
        $pipeline = config('upload.haikang_pipeline');
        $source_prefix = $bucket=='factsource'?'source1':$bucket=='reportsource'?'source2':'source3';
        $key = date('Ymd',time())."/".$source_prefix.substr(md5(time().mt_rand(100,999)),0,20) . '.' . $files->getClientOriginalExtension();
        $fops = config('upload.haikang_format') . '|saveas/' . base64_encode($bucket . ':' . $key);

        $token = $auth->uploadToken($bucket, $key, 3600, ['persistentOps' => $fops, 'persistentPipeline' => $pipeline]);

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $files->getRealPath());

        if (is_null($err)) {

            $data['device_file'] = 'http://reportsource.jtpk668.com/' . $ret['key'];
            // 初始化
            $report_data['uid'] = $userinfo->USERID;
            $report_data['mobile'] = $userinfo->MOBILE;
            $report_data['report_type'] = 47;
            $report_data['locale'] = '';
            $report_data['description'] = '';
            $report_data['way_group'] = null;
            $report_data['way_group_id'] = '1';
            $report_data['origin'] = $type;
            $report_data['plate_number'] = null;
            $report_data['vehicle_color'] = null;
            $report_data['report_time'] = $report_time;
            $report_data['direction'] = null;
            $report_data['imagePath'] = '';
            $report_data['videoPath'] = $data['device_file'] . '#' . $data['device_file'] . '?vframe/jpg/offset/0/w/600/h/600';
            $report_data['file_create_time'] = '0';
            $report_data['file_device_type'] = '';
            $report_data['report_GPS'] = $start_GPS . '#' . $end_GPS;

            if(self::$db->table('report_list')->insert($report_data)){

                return response()->json(['status_code' => 200, 'data' => ['create_time' => date('Y-m-d H:i:s', time())]]);

            }else{

                return response()->json(['status_code' => 500,'msg'=>'System is error']);
            }
        }

		return response()->json(['status_code' => 500,'msg'=>'token is error']);

	}

    /**
     * kc一键举报
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function device_report_kc(Request $request){
    
        $mobile = $request->input('mobile', '');
        $device_id = $request->input('device_id', '');
        $report_time = $request->input('report_time', '');
        $locale = $request->input('locale', '');
        $start_GPS = $request->input('start_GPS', null);
        $end_GPS = $request->input('end_GPS', null);
        $direction = $request->input('direction', null);
        $device_file = $request->input('file_url', '');
        // $type = 'kc';
        $api_url = 'https://api.jtpk668.com/web/';
    
        if (!$device_id || !$report_time || !$locale || !$start_GPS || !$device_file || !$mobile) {
        
            return response()->json(['status_code' => 400, 'msg' => '参数不足']);
        
        } else {
        
            // 违法时间与现实时间超过24小时，返回错误
            if (time() - strtotime($report_time) > 86400) {
    
                return response()->json(['status_code' => 407, 'msg' => '违法时间超过24小时，无法举报']);
            }
            // 地址不进行转换
            $locate = $this->getLocate($locale, $start_GPS);
        
            //2.获取上传文件路径，上传到七牛
            // 使用新版上传
            $qiniu_config = array(
                'accessKey' => config('upload.accessKey'),
                'secretKey' => config('upload.secretKey'),
                'bucket'    => config('upload.bucket_report'),
                'domain'    => config('upload.bucket_report_domain'),
            );
            $upload_to_qiniu = new UploadToQiniu($qiniu_config);
            $upload_result = $upload_to_qiniu->fetch($device_file);
        
            if ($upload_result['status']){
            
                $result = curlinfo_header('POST', $api_url . 'recorder_kc_report', [], [
                    'mobile' => $mobile,
                    'device_id' => $device_id,
                    'report_time' => $report_time,
                    'locale' => $locate,
                    'description' => $locale,
                    'start_GPS' => $start_GPS,
                    'end_GPS' => $end_GPS,
                    'direction' => $direction,
                    'file_key' => $upload_result['key']
                ]);
                
                // 每次的日志写入到文件中
                file_put_contents('report_log/' . date('Ymd', time()) . '.log', 'mobile:' . $mobile . '|' . 'time:' . date('Y-m-d H:i:s', time()) . '|' . $result . "\r\n", FILE_APPEND);
    
                $result = json_decode($result, true);
            
                if ($result['status_code'] == 200) {
                    // 举报成功
                    return response()->json(['status_code' => 200, 'data' => ['create_time' => date('Y-m-d H:i:s', time())]]);
                }else {
                    
                    
                
                    return response()->json(['status_code' => $result['status_code'] ? $result['status_code'] : '200', 'msg' => $result['msg'] ? $result['msg'] : '']);
                }
            }
            
            return response()->json(['status_code' => 440, 'msg' => '文件上传错误']);
        
        }

    }


    /**
     * 注册设备
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function device_register(Request $request){

        $data['mobile'] = $request->input('mobile', null);
        $data['device_id'] = $request->input('device_id', null);

        $api_url = 'https://api.jtpk668.com/web/';

        // 参数不足
        if (in_array(null, $data)){
            return response()->json(['status_code' => 400, 'msg' => '参数不足']);
        }

        // 查看手机是否被注册，未注册则注册新账号
        $userinfos = json_decode(curlinfo_header('GET', $api_url . 'user/isexists?mobile=' . $data['mobile'], [], []), true);

        if ($userinfos['data']) {
            $uid = $userinfos['data']['USERID'];
            // 子账号不能绑定设备
            $multi_account = new MultipleAccounts($uid);
            
            if ($multi_account->isSecond($uid)){
                
                return response()->json(['status_code' => 401, 'msg' => '该账号无法绑定设备']);
            }
            // 用户再次随机密码并发送短信
            curlinfo_header('POST', $api_url . 'user/resetpwd', [], ['uid' => $uid, 'mobile' => $userinfos['data']['USERNAME']]);
        }else{
            // 用户注册
            $users = json_decode(curlinfo_header('POST', $api_url . 'user/signup', [], ['mobile' => $data['mobile'], 'type' => 'web']), true);
            if ($users['status_code'] == 200 || $users['status_code'] == 555) {
                $uid = $users['uid'];
            }else{
                return response()->json(['status_code' => 403, 'msg' => '非法信息']);
            }
        }
        // 查看设备号是否被绑定
        $device = self::$db->table('paike_device')->where('uid', '=', $uid)->where('device_id', '=', $data['device_id'])->first();

        if (isset($device->type)){
            return response()->json(['status_code' => 405, 'msg' => '设备已经被绑定']);
        }

        // 绑定设备
        $bind = self::$db->table('paike_device')->insert([
            'uid' => $uid,
            'device_id' => $data['device_id'],
            'type' => ''
        ]);

        if ($bind){
            return response()->json(['status_code' => 200, 'msg' => '设备注册成功']);
        }else{
            return response()->json(['status_code' => 402, 'msg' => '设备注册失败']);
        }

    }
    
    /**
     * 另一个好好开车公司上传方法
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function device_report_kc2(Request $request)
    {
        return response()->json(['status_code' => 200, 'msg' => '接口调用成功']);
    }
    
    
    /**
     * 根据经纬度获取地址
     * @param $address
     * @param $gps
     */
    private function getLocate($address, $gps)
    {
        $url = 'http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=' . str_replace('#', '', $gps) . '&coordtype=wgs84ll&output=json&ak=zoHW24vzeo5fdQV7MfUN9NN2zY5ci6nF';
        
        $result = json_decode(substr(str_replace('renderReverse&&renderReverse(', '', curlinfo_header('POST', $url, [], [])), 0, -1), true);
        
        if ($result['status'] == 0 && $result['result']['formatted_address']) {
            
            return $result['result']['formatted_address'];
        }
        
        return $address;
    }
    
    
    /**
     * 测试
     *
     * @param Request $request
     */
    public function test(Request $request)
    {
        
        $url = $request->input('url');
    
        $qiniu_config = array(
            'accessKey' => config('upload.accessKey'),
            'secretKey' => config('upload.secretKey'),
            'bucket'    => config('upload.bucket_report'),
            'domain'    => config('upload.bucket_report_domain'),
        );
        $upload_to_qiniu = new UploadToQiniu($qiniu_config);
        $upload_result = $upload_to_qiniu->ttt($url);
        
        print_r($upload_to_qiniu->token());
    }


}
